package org.example.unsafe;

import lombok.Data;
import lombok.SneakyThrows;
import sun.misc.Unsafe;

/**
 * @author zhengdp
 * @Description Unsafe对象 -- CAS操作
 *  线程安全的修改 Teacher对象的属性
 * @Date 2022/11/27 20:20
 * @Created by zhengdp
 */
public class UnsafeCas {
    @SneakyThrows
    public static void main(String[] args) {
        Unsafe unsafe = UnsafeAccessor.getUnsafe();

        Teacher teacher = new Teacher();

        // 1. 获取域（属性）的偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

        // 2. 执行CAS操作
        unsafe.compareAndSwapInt(teacher,idOffset,0,123);
        unsafe.compareAndSwapObject(teacher,nameOffset,null,"教师1");

        System.out.println(teacher);
    }
}

@Data
class Teacher {
    volatile int id;
    volatile String name;
}
